const {rules, valid} = require("../../utils/rules");
const sqlOptions = require("../../sql");
const user = require("express").Router()
const jwt = require("jsonwebtoken")
const path = require("path");
const multer = require("multer");
const {handleImage} = require("../../handler/handleImage");
const fs = require("fs");
const dirPath = path.resolve(__dirname, '../../static/user/')
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, dirPath); // 他会放在当前目录下的 /upload 文件夹下（没有该文件夹，就新建一个）
    },
    filename: function(req, file, cb) { // 在这里设定文件名
        cb(null, req.rows.id + '-' + file.originalname); // file.originalname是将文件名设置为上传时的文件名，file中携带的
    }
})

const loginRules = [
    {
        name: "username",
        message: "用户名"
    },
    {
        name: "password",
        message: "密码"
    }
]

const registerRules = [].concat(loginRules, [{
    name: "phone",
    message: "手机号"
}])

user.post("/login", rules(loginRules), valid, async (req, res) => {
    try {
        const {username, password} = req.body
        const userList = await req.db.query(sqlOptions({
            name: "sms_user",
            method: "list",
            data: {
                username
            }
        }))
        if (userList.length) {
            const users = userList[0]
            if (password === users.password) {
                const token = jwt.sign({
                    username,
                    id: users.id
                }, 'sms', {
                    expiresIn: '30d'
                })
                return res.status(200).send({
                    code: 200,
                    message: "登录成功",
                    data: {
                        token,
                        user: {
                            username,
                            id: users.id,
                            phone: users.phone
                        }
                    }
                })
            }
            return res.status(200).send({
                code: 400,
                message: "密码错误",
                data: ""
            })
        }
        return res.status(200).send({
            code: 400,
            message: "用户名没有注册无法登录",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})

user.post("/register", rules(registerRules), valid, async (req, res) => {
    try {
        const {username, password, phone} = req.body
        const userList = await req.db.query(sqlOptions({
            name: "sms_user",
            method: "list",
            data: {
                username
            }
        }))
        if (userList.length) {
            return res.status(200).send({
                code: 400,
                message: "当前用户名以注册无法继续注册",
                data: ""
            })
        }
        const phoneList = await req.db.query(sqlOptions({
            name: "sms_user",
            method: "list",
            data: {
                phone
            }
        }))
        if (phoneList.length) {
            return res.status(200).send({
                code: 400,
                message: "当前手机号已被使用",
                data: ""
            })
        }
        await req.db.query(sqlOptions({
            name: "sms_user",
            method: "save",
            data: {
                phone,
                username,
                password
            }
        }))
        return res.status(200).send({
            code: 200,
            message: "注册成功",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})

user.get("/query", async (req, res) => {
    try {
        const id = req.rows.id
        const users = await req.db.query(sqlOptions({
            name: "sms_user",
            data: {
                id
            },
            method: "list"
        }))
        if (users.length) {
            return res.status(200).send({
                code: 200,
                message: "",
                data: users[0]
            })
        }
        return res.status(200).send({
            code: 400,
            message: "系统错误",
            data: ""
        })
    }catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})

user.post("/update", async (req, res) => {
    try {
        const {id, username, phone, sex} = req.body
        await req.db.query(sqlOptions({
            name: "sms_user",
            method: "update",
            key: {
                id
            },
            data: {
                username,
                sex,
                phone
            }
        }))
        return res.status(200).send({
            code: 200,
            message: "保存成功",
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})

// 图片上传
user.post("/image", multer({storage}).single("file"), async (req, res) => {
    try {
        const id = req.rows.id
        await req.db.query(sqlOptions({
            name: "sms_user",
            method: "update",
            key: {
                id
            },
            data: {
                pic: req.file.filename
            }
        }))
        return res.status(200).send({
            code: '200',
            message: '图片上传成功',
            data: req.file.filename
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 图片获取
user.get("/getImage", async (req, res) => {
    try {
        const id = req.rows.id
        const pics = await req.db.query(sqlOptions({
            name: "sms_user",
            method: "list",
            data: {
                id
            },
            select: 'pic'
        }))

        if (pics.length) {
            return res.status(200).send({
                code: 200,
                message: '',
                data: pics[0]
            })
        }
        return res.status(200).send({
            code: 200,
            message: '',
            data: ''
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }
})
// 删除图片
user.post("/delImage", async (req, res) => {
    try {
        const {pic} = req.body
        const id = req.rows.id
        fs.unlinkSync(path.resolve(dirPath, pic))
        await req.db.query(sqlOptions({
            name: "sms_user",
            method: "update",
            data: {
                pic: ""
            },
            key: {
                id
            }
        }))
        return res.status(200).send({
            code: 200,
            message: '图片删除成功',
            data: ""
        })
    } catch (e) {
        return res.status(500).send({
            code: 500,
            message: "系统错误",
            data: ""
        })
    }

})

module.exports = user